package cn.wei.sdd.sms.controller.api;

import cn.wei.common.exception.Assert;
import cn.wei.common.result.R;
import cn.wei.common.result.ResponseEnum;
import cn.wei.common.utils.RandomUtils;
import cn.wei.common.utils.RegexValidateUtils;
import cn.wei.sdd.sms.client.CoreUserClient;
import cn.wei.sdd.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: wei
 * @Date: 2021/10/17/22:59
 */
@RestController
@RequestMapping("/wxApi/sms")
@Api(tags = "短信管理")
@Slf4j
public class ApiSmsController {
    @Resource
    private CoreUserClient coreUserInfoClient;

    @Resource
    private SmsService smsService;

    @Resource
    private RedisTemplate redisTemplate;

    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(@PathVariable String mobile){
        //手机号码不能为空
        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        //是否是合法的手机号码
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile),ResponseEnum.MOBILE_ERROR);

//        //检验手机号是否注册
        Boolean result = coreUserInfoClient.checkMobile(mobile);
        System.out.println(result);
        Assert.isTrue(result==false,ResponseEnum.MOBILE_EXIST_ERROR);

        //生成验证码
        String code= RandomUtils.getFourBitRandom();
        smsService.send(mobile,code);

        //将验证码存入redis中
        redisTemplate.opsForValue().set("sdd:sms:code:"+mobile,code,5, TimeUnit.MINUTES);
        return R.ok().message("短信发送成功");
    }
}
